var express = require('express');
var router = express.Router();
var User = require('../models/user');
require('../../src/util/util');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

/* 登录功能 */
router.post("/login", function (req,res,next) {
  var param = {
    userName:req.body.userName,
    userPwd:req.body.userPwd
  }
  User.findOne(param, function (err,doc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      });
    }else{
      if(doc){// 用户名及密码正确
        res.cookie("userId",doc.userId,{
          path:'/',
          maxAge:1000*60*60
        });
        res.cookie("userName",doc.userName,{
          path:'/',
          maxAge:1000*60*60
        });
        res.json({
          status:'0',
          msg:'',
          result:{
            userName:doc.userName
          }
        });
      }else{
        res.json({// 用户名或密码错误，这里只需返回空的数据，错误信息让前端的默认错误信息显示即可
          status:'',
          msg:'',
          result:''
        });
      }
    }
  });
});

/* 登出接口 */
router.post('/logout',function (req,res,next){
  res.cookie("userId",'',{
    path:'/',
    maxAge: -1
  })
  res.json({
    status: '0',
    msg:'',
    result:''
  })
})

/* 检查登录状态 */
router.get('/checkLogin', function (req,res,next) {
  if(req.cookies.userId){
    res.json({
      status: '0',
      msg: '',
      result:req.cookies.userName
    })
  }else{
    res.json({
      status: '1',
      msg: '未登录',
      result:''
    })
  }
});

/* 获取购车信息 */
router.get('/cartList', function (req,res,next) {
  var userId = req.cookies.userId;
  User.findOne({userId:userId},function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result:''
      })
    }else{
      if(doc){
        res.json({
          status: '0',
          msg: '',
          result: doc.cartList
        })
      }
    }
  })
});

/* 删除购物车中的商品 */
router.post('/cartDel',function (req,res,next) {
  var userId = req.cookies.userId,productId = req.body.productId;
  User.update({ //mongoose中更新数据的api
    userId: userId
  },{
    $pull:{
      'cartList':{
        'productId':productId
      }
    }
  },function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result:''
      })
    }else{
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      })
    }
  })
});

/* 更新购车的商品数量或者单个商品选中状态 */
router.post('/cartEdit',function (req,res,next) {
  var userId = req.cookies.userId,
    productId = req.body.productId,
    productNum = req.body.productNum,
    checked = req.body.checked;
  User.update({"userId":userId,"cartList.productId":productId},{
    "cartList.$.productNum":productNum, // 更新数量
    "cartList.$.checked":checked, // 更新选中状态
  },function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result:''
      })
    }else{
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      })
    }
  })
});

/* 更新全选或者非全选状态 */
router.post('/editCheckALL',function (req,res,next){
  var userId = req.cookies.userId,
    checkAll = req.body.checkAll ? '1' : '-1';
  User.findOne({userId:userId},function (err,user) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    }else{
      if(user){
        user.cartList.forEach(item => {
          item.checked = checkAll;
        });
        user.save(function (err1,doc) {
          if(err1){
            res.json({
              status: '1',
              msg: err.message,
              result:''
            })
          }else{
            res.json({
              status:'0',
              msg:'',
              result:'suc'
            });
          }
        });
      }
    }
  })
});

/* 获取用户地址 */
router.get('/addressList',function (req,res,next) {
  var userId = req.cookies.userId;
  User.findOne({userId:userId},function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    }else{
      res.json({
        status: '0',
        msg: '',
        result: doc.addressList
      })
    }
  })
});

/* 设置用户默认地址 */
router.post('/setDefault',function (req,res,next) {
  var userId = req.cookies.userId,
      addressId= req.body.addressId;
  User.findOne({userId:userId},function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    }else{
      if(doc){
        doc.addressList.forEach((item) => {
          if(item.addressId == addressId){
            item.isDefault = true;
          }else{
            item.isDefault = false;
          }
        });
        doc.save(function (err1,doc1) {
          if(err1){
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          }else{
            res.json({
              status: '0',
              msg: '',
              result: 'suc'
            })
          }
        })
      }
    }
  })
});

/* 删除用户地址 */
router.post('/delAddress',function (req,res,next){
  var userId = req.cookies.userId,
      addressId = req.body.addressId;
  User.update({ //mongoose中更新数据的api
    userId: userId
  },{
    $pull:{
      'addressList':{
        'addressId':addressId
      }
    }
  },function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result:''
      })
    }else{
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      })
    }
  })
});

/* 生成订单信息 */
router.post('/payment',function (req,res,next) {
  var userId = req.cookies.userId,
      orderTotal = req.body.orderTotal,
      addressId =req.body.addressId;

  User.findOne({userId:userId},function (err,doc) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result:''
      })
    }else{
      var address='',goodList = [];
      // 获取用户地址的详细信息
      doc.addressList.forEach(item => {
        if(item.addressId == addressId){
          address = item;
        }
      });
      // 获取用户在购物车中选择的商品
      doc.cartList.forEach(item =>{
        if(item.checked == '1'){
          goodList.push(item);
        }
      });
      var platform = "666",
          r1 = Math.floor(Math.random()*10),
          r2 = Math.floor(Math.random()*10),
          sysDate = new Date().Format('yyyyMMddhhmmss'),
          createDate = new Date().Format('yyyy-MM-dd hh:mm:ss'),
          orderId = platform + r1 + sysDate + r2;
      // 用户订单信息汇总
      var order = {
        orderId:orderId,
        orderTotal: orderTotal,
        addressInfo: address,
        goodsList: goodList,
        orderStatus:'1',
        createDate: createDate
      }
      // 存入数据库
      doc.orderList.push(order);
      doc.save(function (err,doc1) {
        if(err){
          res.json({
            status: '1',
            msg: err.message,
            result:''
          })
        }else{
          res.json({
            status: '0',
            msg: '',
            result:{
              orderId: order.orderId,
              orderTotal: order.orderTotal
            }
          })
        }
      })
    }
  })
});

/* 查询用户订单详情 */
router.get('/orderDetail',function (req,res,next) {
  var userId = req.cookies.userId,
      orderId = req.param("orderId"),
      orderTotal = 0;
  User.findOne({userId:userId},function (err,userInfo) {
    if(err){
      res.json({
        status: '1',
        msg: err.message,
        result:''
      })
    }else{
      var orderList = userInfo.orderList;
      if(orderList.length > 0){
        console.log('orderId'+orderId);
        orderList.forEach(item => {
          console.log('item.orderId'+item.orderId);
          if(item.orderId === orderId){
            orderTotal = item.orderTotal;
          }
        });
        if(orderTotal > 0){
          res.json({
            status: '0',
            msg: '',
            result:{
              orderId: orderId,
              orderTotal: orderTotal
            }
          })
        }else{
          res.json({
            status: '102',
            msg:'订单不存在' ,
            result:''
          })
        }
      }else{
        res.json({
          status: '101',
          msg: '用户当前无订单',
          result:''
        })
      }
    }
  })
});

/* 查询购物车商品数量 */
router.get('/getCartCount',function (req,res,next) {
  if(req.cookies.userId){
    var userId = req.cookies.userId;
    User.findOne({userId:userId}, function (err,doc) {
      if(err){
        res.json({
          status: '1',
          msg: err.message,
          result:''
        })
      }else{
        var cartList = doc.cartList,
            cartCount = 0;
        cartList.forEach((item => {
          cartCount += item.productNum;
        }));
        res.json({
          status: '0',
          msg: '',
          result: cartCount
        })
      }
    })
  }
});

module.exports = router;
